package com.cskaoyan.config;

import com.cskaoyan.shiro.CustomRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

@Configuration
public class ShiroConfig {


    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm realm, DefaultWebSessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //默认的认证器ModularRealmAuthenticator和默认的授权器ModularRealmAuthorizer
        //realm(s) → 自定义的Realm
        securityManager.setRealm(realm);
        //如果要写自定义的认证器和授权器
        //→ 继承默认的认证器和授权器 → 也可以实现Authenticator、Authorizer接口
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //认证失败 → 重定向的请求url → 默认值login.jsp
        //shiroFilter.setLoginUrl();
        //使用里面的Filter的时候，需要使用到SecurityManager
        shiroFilter.setSecurityManager(securityManager);
        //key 请求url
        //value filter → anon(匿名)、authc(认证)、perms(授权)
        //有序的Map
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/admin/auth/login", "anon");
        //filterChainDefinitionMap.put("/admin/user/list", "perms[user:list]");
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilter;
    }

    //advisor
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
